var sha1 = require('sha1');
var express = require('express');
var router = express.Router();

var User = require('../lib/mongo').User;
var checkNotLogin = require('../middlewares/check').checkNotLogin;

// POST /signin 用户登录
router.post('/', checkNotLogin, function (req, res, next) {
    var userName = req.fields.userName;
    var password = req.fields.password;
    console.log(userName+" "+password);
// heloo
    User.findOne({userName: userName}).exec()
        .then(function (user) {
            if (!user) {
                res.send({error:"用户不存在"})
                return ;
            }
            // 检查密码是否匹配
            if (sha1(password) !== user.password) {
                res.send({error:"用户名或密码错误"})
                return ;
            }
            // 用户信息写入 session
            delete user.password;
            req.session.user = user;
            res.send(user);
        })
        .catch(next);
});

module.exports = router;
